package com.eric.code.oauth2.my;

import com.eric.code.oauth2.common.BaseService;
import com.eric.code.oauth2.login.LoginService;
import com.eric.code.oauth2.model.User;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;

import java.util.Date;

/**
 * Created by eric on 17-3-23.
 */
public class MyService extends BaseService{

    public static final MyService me = new MyService();
    private final User dao = new User().dao();

    public Page<User> paginate(int pageNumber, int pageSize) {
        return dao.paginate(pageNumber, pageSize, "select * ", "from oauth2_user order by createAt desc");
    }

    public Page<User> paginate(int pageNumber) {
        return dao.paginate(pageNumber, PAGE_SIZE, "select * ", "from oauth2_user order by createAt desc");
    }

    /**
     * 初始化默认密码 123456
     * @param user
     */
    public void save(User user){
        user.setCreateAt(new Date());
        user.setPassword("123456");
        user.save();
    }

    /**
     * 修改用户信息
     * @param user
     */
    public void update(User user){
        user.setUserName(user.getEmail());
        user.update();
        LoginService.me.resetUserCache(user);
    }

    public Ret updatePassword(String oldPassword,String newPassword,User user){
        String md5pass = HashKit.md5(oldPassword);
        if(user.getPassword().equals(md5pass)){
            user.setPassword(HashKit.md5(newPassword));
            user.update();
            LoginService.me.resetUserCache(user);
            return Ret.ok();
        }
        return Ret.fail("msg","原密码不正确");
    }
}
